﻿using System;
using System.Data;
using System.IO;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NguyenHoa.Web.App_Code;
using DevExpress.Web.ASPxUploadControl;
using NguyenHoa.Data;
using NguyenHoa.Domains;
using NguyenHoa.Services;

namespace NguyenHoa.Web.Admin
{
  public partial class NewsDetail : AdminBasePage
  {
    #region Properties
    private const int ThumbnailSize = 110;
    private string UploadSession = "TempUploadImage_NewsDetail";

    internal override int RequiredPermission
    {
      get
      {
        switch (NewsType)
        {
          case NewsCategoryType.Normal:
            return (int)FunctionList.AdNews;
          //case NewsCategoryType.Promotion:
          //  return (int)FunctionList.Promotion;
        }
        return (int)FunctionList.AdNews;
      }
    }

    private string NewsType
    {
      get
      {
        string newsType = string.Empty;
        if (Request.QueryString["t"] != null)
          newsType = Request.QueryString["t"].ToString().ToUpper();
        if (newsType != NewsCategoryType.Normal && newsType != NewsCategoryType.Promotion)
          return string.Empty;
        return newsType;
      }
    }

    private int NewsId
    {
      get
      {
        int newsId = 0;
        if (Request.QueryString["id"] != null)
          int.TryParse(Request.QueryString["id"].ToString(), out newsId);
        else
          int.TryParse(hfNewsId.Value, out newsId);
        return newsId;
      }
    }

    private int? CategoryId
    {
      get
      {
        int categoryId = -1;
        if (Request.QueryString["tid"] != null)
          int.TryParse(Request.QueryString["tid"].ToString(), out categoryId);
        if (categoryId != -1) return categoryId;
        else return null;
      }
    }
    #endregion

    #region Methods
    private void LoadPage()
    {
      if (String.IsNullOrEmpty(NewsType))
        Response.Redirect("NewsList.aspx?t=" + NewsCategoryType.Normal);

      hfNewsId.Value = NewsId.ToString();

      cbxCategory.DataSource = new NewsService().GetAllNewsCategory(NewsType, CurrentLanguage.Id, CurrentLanguage.Id);
      cbxCategory.DataBind();

      xdsNewsStatus.DataFile = XmlStatusFile;
      xdsLanguage.DataFile = XmlStatusFile;

      hfTypeId.Value = NewsType;

      int settingPage = 0;
      if (Request.QueryString["sid"] != null)
        int.TryParse(Request.QueryString["sid"].ToString(), out settingPage);
      hfSettingPage.Value = settingPage.ToString();
      ImageUpload1.UploadSessionName = UploadSession;

    }

    private void LoadInfo()
    {
      string imagePath = string.Empty;
      if (NewsId <= 0)
      {
        lblPostedDate.Text = DateTime.Now.ToShortDateString();
        lblPostedBy.Text = CurrentUser.Fullname;
        cbxStatus.Value = NewsStatus.Pending;
        ckbHotNews.Checked = false;
        if (CategoryId != null) cbxCategory.Value = CategoryId;
        else cbxCategory.SelectedIndex = 0;
        //ckbIsActive.Checked = false;
        //cbxLanguage.Value = CurrentLanguage.Id;
      }
      else
      {
        Domains.News news = new NewsService().GetById(NewsId);
        if (news != null)
        {
          NewsCategory cate = new NewsCategoryService().GetById(news.CategoryId);

          lblPostedDate.Text = (news.PostDate.HasValue) ? news.PostDate.Value.ToString("d") : string.Empty;
          lblPostedBy.Text = news.CreatedBy;
          cbxStatus.Value = news.Status;
          lblApprovedDate.Text = (news.ApprovedDate.HasValue) ? news.ApprovedDate.Value.ToString("d") : string.Empty;
          //cbxLanguage.Value = (cate.LanguageId.HasValue) ? cate.LanguageId.Value : CurrentLanguage.Id;
          cbxCategory.Value = news.CategoryId;
          lblApprovedBy.Text = news.ApprovedBy;
          ckbHotNews.Checked = (news.IsHotNews.HasValue) ? news.IsHotNews.Value : false;
          //ckbIsActive.Checked = (news.IsActive.HasValue) ? news.IsActive.Value : false;
          /*
           if (news.Status == NewsStatus.Approval)
           {
               btnSave.ClientEnabled = false;
               ImageUpload1.HideUpload();
           }
           //*/
          ImageUpload1.ImagePath = imagePath;
          if (File.Exists(MapPath("../" + news.ImagePath)))
            imagePath = "../" + news.ImagePath;
        }
      }
      ckbCanApprove.Checked = CanApprove;
    }

    private void LoadContent()
    {
      string title = string.Empty;
      string summary = string.Empty;
      string content = string.Empty;
      string imgPath = FolderDirector.PreviewImage;
      NewsService nService = new NewsService();
      Domains.News news = nService.GetById(NewsId);
      //image.ImageUrl = imgPath;
      if (news != null)
      {
        if (news.Status == NewsStatus.Approval) cbxStatus.Enabled = false;
        title += news.Title;
        summary += news.Summary;
        content = (news.Content != null) ? news.Content : string.Empty;
        ImageUpload1.ImagePath = news.ImagePath;
        if (!string.IsNullOrEmpty(news.ImagePath))
        {
          if (File.Exists(MapPath("../" + news.ImagePath)))
            imgPath = "../" + news.ImagePath;
        }
      }
      txtTitle.Text = title;
      mmSummary.Text = summary;
      htmlEditor.Html = content;
    }

    private string SaveNews(string imagePath)
    {
      //Check Modify Permission
      if (!CanModify)
        return Resources.Messages.ERR0064;

      bool approval = false;
      NewsService nService = new NewsService();
      Domains.News news = null;
      try
      {
        int languageId = CurrentLanguage.Id;
        int categoryId = Convert.ToInt32(cbxCategory.Value);
        string title = txtTitle.Text;
        string summary = mmSummary.Text;
        string content = htmlEditor.Html;
        string approvedBy = string.Empty;
        DateTime? approvedDate = null;
        string status = NewsStatus.Pending;
        bool isHotNews = ckbHotNews.Checked;
        bool isActive = true;

        if (title.Length > LimitLength.Title)
          return String.Format(Resources.Messages.ERR0052, new object[] { Resources.Strings.Title, LimitLength.Title });
        if (summary.Length > LimitLength.Summary)
          return String.Format(Resources.Messages.ERR0052, new object[] { Resources.Strings.Summary, LimitLength.Summary });


        status = cbxStatus.Value.ToString();
        if (cbxStatus.Enabled)
        {
          if (status == NewsStatus.Approval)
          {
            approvedBy = CurrentUser.Fullname;
            approvedDate = DateTime.Now;
            approval = true;
          }
          if (approval)
          {
            if (!CanApprove)
              return Resources.Messages.ERR0016;
          }
        }

        if (!string.IsNullOrEmpty(ImageUpload1.ImagePath))
          imagePath = ImageUpload1.ImagePath;

        if (NewsId > 0)
        {
          news = nService.GetById(NewsId);
          if (news == null)
            return Resources.Messages.ERR0003;
        }
        else
        {
          news = new Domains.News();
          news.CreatedBy = CurrentUser.Fullname;
          news.PostDate = DateTime.Now;
          news.Status = NewsStatus.Pending;
          news.CategoryId = categoryId;
          news.ViewCount = 0;

        }
        if (Session[UploadSession] != null)
        {
          string error = Utils.SaveFileFromTemp(Session[UploadSession].ToString(), MapPath("../" + ImageUpload1.ImagePath));
          if (string.IsNullOrEmpty(error))
            news.ImagePath = ImageUpload1.ImagePath;
        }
        news.Title = title;
        news.Code = VietnameseString.Convert(title);
        news.Summary = summary;
        news.Content = content;
        news.IsHotNews = isHotNews;
        news.IsActive = isActive;
        if (cbxStatus.Enabled)
        {
          news.Status = status;
          news.ApprovedBy = approvedBy;
          news.ApprovedDate = approvedDate;
        }
        news.Type = NewsType;
        news.CategoryId = categoryId;
        //news.LanguageId = languageId;
        nService.Save(news);
        Session[UploadSession] = null;
      }
      catch (Exception ex)
      {
        WriteLog("NewsDetail.aspx::Save News", ex);
        return Resources.Messages.ERR0004;
      }
      if (approval)
      {

        return "OK|" + news.Id + "|Approval|" + CurrentUser.Fullname + "|" + news.ApprovedDate.Value.ToShortDateString();
      }
      return "OK|" + news.Id;
    }
    #endregion

    #region Events
    protected void Page_Load(object sender, EventArgs e)
    {

      LoadPage();
      if (!IsPostBack && !IsCallback)
      {
        LoadInfo();
        LoadContent();
      }
    }

    protected void ctrlCallback_Callback(object source, DevExpress.Web.ASPxCallback.CallbackEventArgs e)
    {
      string[] para = e.Parameter.Split('|');
      if (para[0] == "Save")
      {
        e.Result = SaveNews(para[1]);
      }
    }
    #endregion
  }
}
